package com.bee.app.service;

import java.util.Date;

import org.apache.log4j.Logger;

import com.bee.app.express.XM58Express;
import com.bee.app.model.ExpressCache;
import com.bee.app.util.DateUtil;
import com.bee.app.util.FastJsonUtil;
import com.bee.app.util.StringKit;
import com.bee.app.vo.ExpressQueryVo;

/**
 * 快递的业务处理
 *
 * @author liuzy
 * @date 2015年6月5日
 */
public class ExpressService extends BaseService {

	private Logger logger = Logger.getLogger(ExpressService.class);
	
	public static final ExpressService service = new ExpressService();

	/**
	 * 快递查询
	 *
	 * @param userId
	 * @param expressNumber
	 * @return
	 */
	public ExpressQueryVo query(String userId, String expressNumber) {
		String detail = null;
		String sql = "select * from bee_express_cache where userId=? and expressNumber=?";
		ExpressCache expressCache = ExpressCache.dao.findFirst(sql, userId, expressNumber);
		if (expressCache == null) {
			detail = XM58Express.query(expressNumber);
			if (!StringKit.isNullOrEmpty(detail)) {
				new ExpressCache()
					.put("userId", userId)
					.put("expressNumber", expressNumber)
					.put("detail", detail)
					.save();
			}
		} else {
			Date updateTime = expressCache.getDate("updateTime");
			// 如果更新时间超过1小时,再次从接口获取
			long now = new Date().getTime();
			long time = updateTime.getTime();
			logger.info("当前时间:" + DateUtil.format(now));
			logger.info("数据时间:" + DateUtil.format(time));
			logger.info("相差时间:" + (now - time) / 1000 + "秒");
			if (now - time > (1000 * 60 * 60)) {
				logger.info("重新获取");
				detail = XM58Express.query(expressNumber);
				if (detail != null) {
					new ExpressCache()
						.put("id", expressCache.getInt("id"))
						.put("userId", userId)
						.put("expressNumber", expressNumber)
						.put("detail", detail)
						.update();
				}
			} else {
				logger.info("使用数据库值");
				detail = expressCache.getStr("detail");
			}
		}
		if (!StringKit.isNullOrEmpty(detail)) {
			return FastJsonUtil.fromJSON(detail, ExpressQueryVo.class);
		} else {
			return new ExpressQueryVo();
		}
	}

}
